package com.tuanzi.loan.schedule.receipt.monitor.sender;

import com.tuanzi.loan.schedule.receipt.monitor.ISender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;

@Slf4j
public class EmailSender implements ISender {

    private final JavaMailSender mailSender;
    private final String from;
    private final String to;
    private final String subject;
    private final String content;

    public EmailSender(JavaMailSender mailSender, String from, String to, String subject, String content) {
        this.mailSender = mailSender;
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;
    }

    @Override
    public void send() {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, StandardCharsets.UTF_8.displayName());
            messageHelper.setFrom(from);
            messageHelper.setTo(StringUtils.split(to, ","));
            messageHelper.setSubject(subject);
            messageHelper.setText(content);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("Send email occur error.", e);
        }
    }
}
